package com.meritit.portal.util;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;


/**
 * 资源文件读取辅助类
 * 
 * @author xuejp
 * 
 */
public class PropertiesUtil {

    private static Logger log = Logger.getLogger(PropertiesUtil.class);

    public static Properties prop;

    /**
     * 初始化读取配置文件
     */
    public static void ini() {
        prop = new Properties();
        try {
            InputStream is = getResourceAsStream("ssosystem.config.properties");
            if (is != null) {
            	prop.load(is);
                is.close();
            }
        } catch (Exception e) {
            log.error("读取配置文件出错,错误信息:" + e.getMessage());
        }
    }

    /**
     * 读取配置文件，根据键读取值，返回字符串类型
     */
    public static String getText(String key) {
        String value = "";
        try {
            if(prop == null){
                ini();
            }
            value = prop.getProperty(key);
            if (value == null) {
                return "";
            }
            return value.trim();
        } catch (Exception e) {
            log.error("读取配置文件属性出错,错误信息:" + e.getMessage());
            return value;
        }
    }
    
    /**
     * 读取配置文件，根据键读取值，返回字符串类型
     */
    public static int getInt(String key, int defaultPort) {
        try {
            if(prop == null){
                ini();
            }
            return Integer.parseInt(prop.getProperty(key));
        } catch (Exception e) {
            log.error("读取配置文件属性出错,错误信息:" + e.getMessage());
            return defaultPort;
        }
    }
    public static InputStream getResourceAsStream(String resource) throws Exception {
        String stripped = resource.startsWith("/") ? resource.substring(1)
                : resource;

        InputStream stream = null;
        ClassLoader classLoader = Thread.currentThread()
                .getContextClassLoader();
        if (classLoader != null) {
            stream = classLoader.getResourceAsStream(stripped);
        }
        if (stream == null) {
            stream = PropertiesUtil.class
                    .getResourceAsStream(resource);
        }
        if (stream == null) {
            stream = PropertiesUtil.class.getClassLoader()
                    .getResourceAsStream(stripped);
        }
        if (stream == null) {
            throw new Exception(resource + " not found");
        }
        return stream;
    }

}
